<template>
  <div class="login-bg">
    <div class="login-center">
      <h2>登录</h2>
      <form @submit.prevent="onSubmit">
        <input v-model="form.username" placeholder="用户名" required />
        <input v-model="form.password" type="password" placeholder="密码" required />
        <button type="submit">登录</button>
      </form>
      <div v-if="error" style="color:red">{{ error }}</div>
    </div>
  </div>
</template>
<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
const router = useRouter()
const form = ref({ username: '', password: '' })
const error = ref('')
const onSubmit = async () => {
  error.value = ''
  try {
    const res = await axios.post('/api/login', form.value)
    if (res.data.code !== 200) {
      error.value = res.data.msg || '登录失败'
      return
    }
    sessionStorage.setItem('user', JSON.stringify(res.data.data))
    const role = res.data.data.role
    if (role === 'ADMIN') {
      router.push('/users')
    } else {
      router.push('/buy')
    }
  } catch (e) {
    error.value = e.response?.data?.msg || (e.message || '登录失败，用户名或密码错误')
  }
}
</script>
<style>
.login-bg { width: 100vw; height: 100vh; display: flex; align-items: center; justify-content: center; background: url('https://img0.baidu.com/it/u=1082154065,2379499126&fm=253&fmt=auto&app=138&f=JPEG?w=875&h=500') no-repeat center center; background-size: cover; }
.login-center { width: 320px; padding: 32px; background: #fff; border-radius: 8px; box-shadow: 0 2px 8px #ccc; }
.login-center h2 { text-align: center; margin-bottom: 24px; }
.login-center form { display: flex; flex-direction: column; gap: 16px; }
.login-center input { padding: 8px; border: 1px solid #ccc; border-radius: 4px; }
.login-center button { padding: 8px; border: none; background: #409eff; color: #fff; border-radius: 4px; cursor: pointer; }
</style> 